﻿using System;
using System.Collections.Generic;
using System.Text;

namespace YummyGame.Framework
{
    public class ExpressionVariable : Expression
    {
        private ExpressionContext context;
        private string key;

        public ExpressionVariable(ExpressionContext context, string key)
        {
            this.context = context;
            this.key = key;
        }

        public ExpressionVariable(ExpressionContext context, List<char> chars)
        {
            this.context = context;
            StringBuilder sb = new StringBuilder();
            foreach (var c in chars)
            {
                sb.Append(c);
            }
            this.key = sb.ToString();
        }

        public override void RebindContext(ExpressionContext context)
        {
            this.context = context;
        }

        public override float Calculate()
        {
            if(context == null) throw new Exception("缺少变量运行环境：" + key);
            if (context.LocalVariables.ContainsKey(key)) return context.LocalVariables[key];
            if (context.OwnerVariables.ContainsKey(key)) return context.OwnerVariables[key];
            if (context.GlobalVariables.ContainsKey(key)) return context.GlobalVariables[key];
            throw new Exception("未找到定义的变量：" + key);
        }

        public override object Clone()
        {
            return new ExpressionVariable(context, key);
        }
    }
}
